package com.jzxy.PingFen.controller;

import com.jzxy.PingFen.common.Result;
import com.jzxy.PingFen.mapper.AllMapper;
import com.jzxy.PingFen.pojo.LoginUser;
import com.jzxy.PingFen.pojo.User;
import com.jzxy.PingFen.utils.CacheUtil;
import com.jzxy.PingFen.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:PingFenController
 * Package:com.jzxy.PingFen.controller
 * Description:
 *
 * @Author: dlh
 * @Creat:2025/1/13-14:48
 */
@RestController
@Slf4j
@CrossOrigin
public class PingFenController {

    @Autowired
    private AllMapper allMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private CacheUtil cacheUtil;
    @PostMapping("/login")
    public Result login(@RequestBody User user) throws Exception {
        //AuthenticationManager进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserId(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate==null){
            throw  new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getUserId();
        HashMap<String, Object> claimsMap = new HashMap<>();
        claimsMap.put("userId", userid);
        String token= JwtUtil.createJWT(
                "dlh",
                360000000L,
                claimsMap);
        cacheUtil.set("login:"+userid,loginUser);
        return Result.success("登录成功",token);
//        User dbUser = allMapper.login(user);
//        if (dbUser == null){
//            return Result.error("用户名或密码错误");
//        }else {
//            return Result.success("./score.html?userId="+user.getUserId());
//        }
    }

    @GetMapping("/score")
    @PreAuthorize("hasAnyAuthority('score')")
    public Result getTodayTime(){
        return Result.success("评分成功");
    }



    @GetMapping("/hello")
    @PreAuthorize("hasAnyAuthority('hello')")
    public Result hello(){
        return Result.success("hello");
    }
}
